package leetcode.f1t100;

/**
 * 在矩阵中寻找连续单词(可上下左右), 不可重复使用
 * https://leetcode.com/problems/word-search/
 *
 * @author lichx
 * @createTime 2024/1/29 11:15
 */
public class Q79_WordSearch {

    public boolean exist(char[][] board, String word) {
        char[] chars = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (exist(board, chars, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean exist(char[][] board, char[] chars, int i, int j, int l) {
        if (chars[l] != board[i][j]) {
            return false;
        }
        if (l == chars.length -1 && chars[l] == board[i][j]) {
            return true;
        }
        char temp = board[i][j];
        board[i][j] = 0;
        boolean left = false, right = false, up = false, down = false;
        // up
        if (i - 1 >= 0) {
            up = exist(board, chars, i - 1, j, l + 1);
        }
        // down
        if (i + 1 < board.length) {
            down = exist(board, chars, i + 1, j, l + 1);
        }
        // left
        if (j - 1 >= 0) {
            left = exist(board, chars, i, j - 1, l + 1);
        }
        // right
        if (j + 1 < board[0].length) {
            right = exist(board, chars, i, j + 1, l + 1);
        }

        board[i][j] = temp;
        return left || right || up || down;
    }

    public static void main(String[] args) {
        Q79_WordSearch bean = new Q79_WordSearch();
        char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
        String word = "ABCCED";
        System.out.println(bean.exist(board, word));
    }
}
